package database

import (
	"context"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"server/model"
	"time"
)

type dataBase struct {
	client *mongo.Client
	ctx context.Context
	cancel context.CancelFunc
}

func NewDataBase() dataBase{
	ctx, cancel := context.WithTimeout(context.Background(), 100*time.Second)
	//defer cancel()
	client, _  := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))

	return dataBase{
		client: client,
		ctx: ctx,
		cancel: cancel,
	}
}

func (d *dataBase) FindPictures() []model.Picture {
	collection := d.client.Database("learn-typescript").Collection("picture")
	cursor, _ := collection.Find(d.ctx,bson.D{})
	pictures := make([]model.Picture,100)
	if cursor != nil {
		cursor.All(d.ctx,&pictures)
	}
	return pictures
}

func (d *dataBase) AddPicture(picture model.Picture){
	collection := d.client.Database("learn-typescript").Collection("picture")
	collection.InsertOne(d.ctx,picture)
}

func (d *dataBase) Close() {
	d.client.Disconnect(d.ctx)
}




